package org.recursed.simpleweather.forecast;

import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import org.recursed.simpleweather.WeatherGallery;
import org.xml.sax.helpers.DefaultHandler;

public class FetchForecast extends DefaultHandler implements Runnable {
	
	private static final String HOST = "www.weather.gov";
	private static final int PORT = 80;
	private static final String URL_PREFIX = 
		"/forecasts/xml/sample_products/browser_interface/ndfdXMLclient.php?"+
		"&product=time-series&icons=icons";
		//&lat=38.99&lon=-77.01&begin=2009-02-28T00:00:00&end=2009-03-05T00:00:00

	private static final String LAT = "&lat=";
	private static final String LON = "&lon=";
	private static final String BEGIN = "&begin=";
	private static final String END = "&end=";
	
	private static final DateFormat DATE_FORMAT;
	static {
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'hh':00:00'");
		DATE_FORMAT = df;
	}
	
	private String urlString;
	private WeatherGallery parent;
	
	public FetchForecast(String lat, String lon, WeatherGallery parent) {
		this.parent = parent;
		StringBuilder url = new StringBuilder(URL_PREFIX);
		url.append(LAT).append(lat).append(LON).append(lon);
		Calendar start = Calendar.getInstance();
		Calendar end = Calendar.getInstance();
		end.add(Calendar.DAY_OF_MONTH, 7);
		url.append(BEGIN).append(DATE_FORMAT.format(start.getTime()));
		url.append(END).append(DATE_FORMAT.format(end.getTime()));
		this.urlString = url.toString();
	}
	
	public void run() {
		try {
			System.out.println("Ripping: " + urlString);
			Socket s = new Socket(HOST, PORT);
			OutputStream os = s.getOutputStream();
			PrintWriter out = new PrintWriter(new OutputStreamWriter(os));
			StringBuilder request = new StringBuilder("GET ").append(urlString).append("HTTP/1.1");
			request.append("\n");
			request.append("Host: ").append(HOST).append("\n");
			request.append("\n");
			out.print(request);
			out.flush();
			
			InputStream in = s.getInputStream();
			
			NWSWeatherXMLParser parser = new NWSWeatherXMLParser(in);
			parser.parse(parent);
			System.out.println("Finished parsing");
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	
	
}
